// index.js
import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify';
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
// 获取应用实例
import dayjs from "../../utils/dayjs.min";

const app = getApp()
import {
  get_kebiao,
  get_show
} from "../../api/shool/get_score.js";
import {
  login,
  get_Code,
  login_old
} from '../../api/login/login_user.js';

import {
  login_ff
} from '../../api/ff/login.js'

import {
  RSA,
  ff_RSA
} from '../../lib/password_util.js'
// const RSA = require('../../utils/password_util.js');

Page({

  onClose_1() {
    this.setData({
      show_1: false
    });
  },
  onChange(event) {
    const {
      picker,
      value,
      index
    } = event.detail;

  },
  chang_shoool_type() {
    this.setData({
      show_1: true
    })
  },
  onConfirm(event) {
    const {
      picker,
      value,
      index
    } = event.detail;
    console.log(value)
    this.data.loginTypeName = this.data.shool[index].key

    this.setData({
      shool_name: {
        name: value,
        url: this.data.shool[index].url
      },
      show_1: false
    })
    // Toast(`当前值：${value}, 当前索引：${index}`);
  },

  onCancel() {
    // Toast('取消');
    this.setData({
      show_1: false
    })
  },
  data: {
    show_1: false,
    columns: ['武汉学院', '武汉学院老版登录', '武昌工学院', '武汉工商学院', '测试账号'],
    shool_name: {
      name: '武汉学院',
      url: 'http://www.whxy.edu.cn/__local/B/AB/02/517B1A932EE723DC0BCBDE25920_86C4BE57_1193C.png'
    },
    loginTypeName: 'whxy',
    shool: [{
        key: 'whxy',
        url: 'http://www.whxy.edu.cn/__local/B/AB/02/517B1A932EE723DC0BCBDE25920_86C4BE57_1193C.png'
      },

      {
        key: 'whxy_old',
        url: 'http://www.whxy.edu.cn/__local/B/AB/02/517B1A932EE723DC0BCBDE25920_86C4BE57_1193C.png'
      },
      {
        key: 'wcgxy',
        url: "https://bkimg.cdn.bcebos.com/pic/43a7d933c895d1436a80f20a72f082025aaf0720?x-bce-process=image/resize,m_lfit,w_536,limit_1/format,f_jpg"
      },
      {
        key: 'whgsxy',
        url: "https://t13.baidu.com/it/u=317347638,1442634759&fm=179&app=42&size=w54&n=0&f=JPEG&fmt=auto?s=0FCAAC5A4D9345ED007CB45B030010F5&sec=1660928400&t=e081b5592826d0d21eae1223bd8a450b"
      },
      {
        key: 'cs',
        url: ''
      }
    ],
    option1: [{
        text: '武汉学院',
        value: 0
      },
      {
        text: '新款商品',
        value: 1
      },
      {
        text: '活动商品',
        value: 2
      },
    ],
    value1: 0,

    is_end: false, //是否看完
    beforeClose: (action) => new Promise((resolve) => {
      setTimeout(() => {
        if (action === 'confirm') {
          resolve(false);
        } else {
          // 拦截取消操作
          resolve();
        }
      }, 1000);

    }),
    result: ['a', 'b'],
    show: null,
    url: null,
    type_1: null,
    username: '',
    password: '',

    service: 'http://one.whxy.edu.cn/shiro-cas',
    loginType: '',
    img: '',
    sms: '',
    uuid: '',
    loading: false,
    arr: [
      'https://s2.loli.net/2022/05/29/lUB7usYketgyjoO.png',
      'https://s2.loli.net/2022/05/08/KUE5tGVPav1sLkc.png',
      'https://s2.loli.net/2022/05/08/hJZ9j4bRFO1ED5k.jpg',
      'https://s2.loli.net/2022/05/08/8z2Cb7WUpEGxkAc.png',
      'https://s2.loli.net/2022/05/08/kB7zLOV4aHFQ9uw.png',
      'https://s2.loli.net/2022/05/08/LIxWlOFHZdgCk2m.png'
    ],
  },
  //预览
  yulan(e) {
    console.log(e.currentTarget.dataset.url)
    wx.previewImage({
      current: e.currentTarget.dataset.url,
      //数据源
      urls: this.data.arr
    });
  },

  onClickIcon() {
    Dialog.alert({
      message: '学号密码为学校的新版教务系统学号密码',
      theme: 'round-button',
      closeOnClickOverlay: true
    }).then(() => {
      // on close
    })
  },


  //微信登录
  //登录
  login: function () {
    wx.login({
      success(res) {

        wx_login({
          code: res.code,
        }).then(res => {
          if (res.data.statusCode == 200) {
            //存入用户openid到缓存
            wx.setStorageSync('openid', res.data.data.openid)
          }

        })
      }
    })


  },

  //获取权限
  get_wx_info() {
    wx.getUserProfile({
      desc: '用于显示评论信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {

        //存入用户信息到缓存
        wx.setStorageSync('wx_user_info', res.userInfo)

      }
    })
  },




  //登录
  async login_1(e) {
    wx.reportEvent("a1", {
      "name_1": this.data.username.replace(/\s+/g, '')
    })
    let username = this.data.username.replace(/\s+/g, '')
    let password = this.data.password.replace(/\s+/g, '')
    let code = this.data.sms.replace(/\s+/g, '')

    let reg_num = new RegExp('');
    //验证用户名和密码
    if (username == '') {
      Notify({
        type: 'warning',
        message: '请输入学号'
      });
      this.setData({
        number_error: '请输入学号'
      })
      //判断用户名是否为数字



    } else if (username.length < 6 && (/^[0-9]*$/).test(username)) {
      this.setData({
        number_error: '学号格式错误'
      })
    } else if (password == '') {
      this.setData({
        password_error: '密码不能为空'
      })
    } else if (code == '') {
      this.setData({
        code_error: '验证码不能为空'
      })
    } else {

      this.login_request()


    }
  },

  //登录请求
  login_request() {

    this.setData({
      number_error: ''
    })
    this.data.loading = true
    this.setData({
      loading: this.data.loading
    })
    //去掉空格
    let username = this.data.username.replace(/\s+/g, '')
    let password = this.data.password.replace(/\s+/g, '')
    let fl_pass = password
  
    if (this.data.loginTypeName == 'whxy') { //武汉学院
      password = RSA(password).clear
    } else if (this.data.loginTypeName == 'wcgxy') { //武昌工学院
      password = ff_RSA(password)
    }
console.log(fl_pass);

    login({
      username: username,
      password: password,
      fl1906: RSA(fl_pass).ecodeMsg,
      uuid: this.data.uuid,
      captcha: this.data.sms,
      loginType: 3,
      loginTypeName: this.data.loginTypeName

    }).then(res => {
      if (res.data.statusCode == 200) {
        // if (this.data.username.length == 11 || this.data.username.length == 12) {
        res.data.data.userInfo.info.avatar = res.data.data.data.user.avatar

        wx.setStorage({
          key: 'userinfo',
          data: res.data.data.userInfo.info
        })
        wx.setStorageSync('user', res.data.data.data.user)
        // } else {
        // wx.setStorage({
        //   key: 'userinfo',
        //   data: {
        //     Campus: {
        //       value: "",
        //       key: "所属校区"
        //     },
        //     Department: {
        //       value: "信息工程学院",
        //       key: "院系"
        //     },
        //     Education: {
        //       value: "本科",
        //       key: "学历层次"
        //     },
        //     Enname: {
        //       value: "Su Caihua",
        //       key: "英文名"
        //     },
        //     Grade: {
        //       value: "2019",
        //       key: "年级"
        //     },
        //     Graduation_time: {
        //       value: "2023-06-30",
        //       key: "毕业时间"
        //     },
        //     Level: {
        //       value: "普通本科",
        //       key: "学生类别"
        //     },
        //     avatar: "https://img.flya.top/comment/1651259320768",
        //     class: {
        //       value: "软件工程1904", key: "所属班级"
        //     },
        //     if_present: {
        //       value: "是",
        //       key: "是否有学籍"
        //     },
        //     if_school: {
        //       value: "是",
        //       key: "是否在校"
        //     },
        //     join_shool_time: {
        //       value: "2019-09-01",
        //       key: "入校时间"
        //     },
        //     major: {
        //       value: "",
        //       key: "方向"
        //     },
        //     name: {
        //       value1: "/eams/showSelfAvatar.action?user.name=19202140221",
        //       value: "测试账号",
        //       key: "姓名"
        //     },
        //     nationality: {
        //       value: "汉族",
        //       key: "民族"
        //     },
        //     present_day: {
        //       value: "2019-09-01",
        //       key: "学籍生效日"
        //     },
        //     present_status: {
        //       value: "在校",
        //       key: "学籍状态"
        //     },
        //     project: {
        //       value: "武汉学院",
        //       key: "项目"
        //     },
        //     sex: {
        //       value: "男",
        //       key: "性别"
        //     },
        //     stuNumber: {
        //       value: "19202140221",
        //       key: "学号"
        //     },
        //     stu_type: {
        //       value: "信息工程学院",
        //       key: "教学单位"
        //     },
        //     study_type: {
        //       value: "普通全日制",
        //       key: "学习形式"
        //     },
        //     system: {
        //       value: "4",
        //       key: "学制"
        //     },
        //     tea_unit: {
        //       value: "软件工程",
        //       key: "专业"
        //     },

        //   }
        // })
        // wx.setStorageSync('user', {
        //   avatar: "https://img.flya.top/comment/1651259320768",
        //   birthday: 123345,
        //   crtHost: "192.168.245.1",
        //   crtTime: "2022-03-16 03:39:49",
        //   crtUser: "3",
        //   id: 3111699,
        //   name: "19202140221",
        //   password: "dfx36hRP7PN48xpRoEZKo/OfoDYoSz6450vWgNOgX6s=",
        //   type: "1",
        //   updHost: "10.0.4.8,10.0.4.8",
        //   updName: "193001320240",
        //   updTime: "2022-05-02 23:56:42",
        //   updUser: "4212126",
        //   username: "19202140221",
        // })
        // }
        Notify({
          type: 'success',
          message: '登录成功'
        });




        wx.setStorage({
          key: 'token',
          data: res.data.data.data.token
        })
        if (this.data.login_type == 1) {
          console.log('登录类型1')
          if (!wx.getStorageSync('openid')) {
            this.login()
          }

          if (!wx.getStorageSync('wx_user_info')) {
            this.get_wx_info()
          }

        }

        if (this.data.url) {
          if (this.data.url.indexOf('id') > -1) {
            console.log('跳转')

            wx.switchTab({
              url: this.data.url,

            })
          } else {
            wx.redirectTo({
              url: this.data.url
            })
          }

        } else {

          wx.switchTab({
            url: '/pages/index/index',
          })


        }





      } else if (res.data.statusCode == 400) {
        Notify(res.data.message);
        if (res.data.message == '连接学校服务器超时 请稍后重试') {
          Dialog.alert({
            title: '登陆失败',
            message: '请请检查您的学号密码是否正确，如若再登录失败，您可以尝试登录我们学校的新版教务系统，如果新版教务系统能登上，您可以在更多页面-联系客服询问相关问题',
          }).then(() => {
            // on close
          });
        }

      } else {
        Dialog.alert({
          title: '登陆失败',
          message: '请请检查您的学号密码是否正确，如若再登录失败，您可以尝试登录我们学校的新版教务系统，如果新版教务系统能登上，您可以在更多页面-联系客服询问相关问题',

        }).then(() => {
          // on close
        });
        Notify('登陆失败');
      }
      //   
      this.data.loading = false
      this.setData({
        loading: this.data.loading
      })
    }).catch(err => {
      Notify('连接超时,可能由于第一次登录，请重试');
      this.data.loading = false
      this.setData({
        loading: this.data.loading
      })
    })
  },
  onBeforeClose(action, done) {
    if (action === "confirm") { // 点击确定走这里
      return done(false);
    } else { // 点击取消走这里
      return done(true);
    }

  },

  //授权登录
  shouquan() {

    if (this.data.is_end) {
      wx.setStorageSync('frist_login', true)
      this.setData({
        show: false
      })

    } else {

      Notify({
        type: 'warning',
        message: '请阅读并同意《同学须知》'
      });
      this.setData({
        show: true
      })
      return false;
    }



  },

  //拒绝授权
  onClose: function () {
    wx.exitMiniProgram({
      success() {
        console.log('退出')
      }
    })
  },
  //查看完成
  onLower() {
    wx.vibrateShort({
      type: 'heavy',
      success: res => {
        console.log(res)
      }
    })
    console.log('查看完成')
    this.setData({
      is_end: true
    })
  },


  get_code() {
    get_Code().then(res => {

      this.data.img = 'data:image/png;base64,' + res.data.data.captcha
      this.data.uuid = res.data.data.uuid

      this.setData({
        img: this.data.img
      })
    })
  },

  async onLoad(options) {




    if (wx.getStorageSync('frist_login')) {
      this.setData({
        show: false
      })
    } else {
      this.setData({
        show: true
      })
    }

    this.data.login_type = options.login_type

    this.data.url = options.url
    if (options.id) {
      app.globalData.id = options.id
      app.globalData.time = options.timestamp
      this.data.url = '/pages/index/index?id=' + options.id
    }

    await get_show().then(res => {

      if (res.data.password == app.getVersion()) {
        this.data.type_1 = res.data.stuNumber

      } else {
        this.data.type_1 = 'false'
      }
      if (res.data.phone == 1) {
        this.setData({
          username: '193001320240',
          password: '15271627342Zzf'
        })

      }
    })
    this.setData({
      type_1: this.data.type_1
    })
    this.get_code()
  },

})